package com.minimalist.basic.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.minimalist.basic.config.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author 11987
 */
@Slf4j
@Service
public class FolderCompressorService {

    public void compressAndDeleteFolder(String sourceFolderPath, String zipFilePath) {
        // 压缩文件夹
        compressFolder(sourceFolderPath, zipFilePath);
        // 删除文件夹
        deleteFolder(sourceFolderPath);
    }

    /**
     * 压缩指定文件夹到指定的压缩包路径
     *
     * @param sourceFolderPath 要压缩的文件夹路径
     * @param zipFilePath      压缩包的输出路径
     */
    private void compressFolder(String sourceFolderPath, String zipFilePath) {
        File sourceFolder = new File(sourceFolderPath);
        if (!sourceFolder.exists() || !sourceFolder.isDirectory()) {
            log.error("压缩失败，指定的文件夹不存在或不是文件夹，路径为：{}", sourceFolderPath);
            throw new BusinessException("指定的文件夹不存在或不是文件夹");
        }

        // 使用 Hutool 的 ZipUtil 进行压缩
        ZipUtil.zip(sourceFolderPath, zipFilePath);
        log.info("文件夹已成功压缩到: {}", zipFilePath);
    }

    /**
     * 删除指定文件夹及其所有内容
     *
     * @param folderPath 要删除的文件夹路径
     */
    private void deleteFolder(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            log.error("文件夹不存在，路径为：{}", folderPath);
            throw new BusinessException("文件夹不存在");
        }

        // 使用 Hutool 的 FileUtil 进行删除
        FileUtil.del(folder);
        log.info("文件夹及其内容已成功删除: {}", folderPath);
    }
}
